import { FC, useEffect } from 'react';
import { Modal, Button, Form, Input } from 'antd';
import { SingelUserType } from '../data';

interface UserModalProps {
  userInfo: SingelUserType | undefined;
  isModalVisible: boolean;
  handleCancel: () => void;
  formSubmit: (value: any) => void;
  loading: boolean;
}

//参数中方法 通过hook实现调用
const UserModal: FC<UserModalProps> = (props) => {
  const { userInfo, isModalVisible, handleCancel, formSubmit, loading } = props;
  const [form] = Form.useForm();
  //通过useForm setState  此事form控件尚未加载完成，会提示错误。 通过react hook useEffect处理生命周期问题
  //useEffect(触发函数, 【触发的条件】)
  useEffect(() => {
    if (userInfo === undefined) {
      form.resetFields();
    } else {
      form.setFieldsValue(userInfo);
    }
  }, [isModalVisible]);

  const onOk = () => {
    form.submit();
  };

  return (
    //modal需加forceRender 强制渲染
    <Modal
      title="Basic Modal"
      visible={isModalVisible}
      onOk={onOk}
      onCancel={handleCancel}
      forceRender
      okButtonProps={{ loading: loading }}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        onFinish={formSubmit}
      >
        <Form.Item
          name="name"
          label="名字"
          rules={[{ required: true, message: 'dddddd' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item name="email" label="邮件" rules={[{ type: 'email' }]}>
          <Input />
        </Form.Item>
        <Form.Item name="create_time" label="创建时间">
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UserModal;
